package utils;

package utils;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBCUtils {
    private static String driverClassName;
    private static String url;
    private static String username;
    private static String password;

    //静态代码块,类第一次加载会自动执行一遍,此后不用重复加载
    static {
        try {
            //类加载器
            ClassLoader loader = JDBCUtils.class.getClassLoader();
            //读取配置文件转化为输入流
            InputStream inputStream = loader.getResourceAsStream("utils/properties");
            //Preperties用来处理properties文件,获取里面的信息
            Properties properties = new Properties();
            //把字节输入流的信息加载到properties对象
            properties.load(inputStream);
            driverClassName = properties.getProperty("jdbc.driverClassName");
            url = properties.getProperty("jdbc.url");
            username = properties.getProperty("jdbc.username");
            password = properties.getProperty("jdbc.password");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnection() {
        Connection conn = null;
        try {
            Class.forName(driverClassName);
            conn = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }
    public static void close(Connection con, PreparedStatement pre, ResultSet re) {
        try {
            if (re != null) {
                re.close();
            }
            if (pre != null) {
                pre.close();
            }
            if (con != null) {
                con.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

